package com.sec.android.app.myfiles.info;

import com.sec.android.app.myfiles.log.Log;
import com.sec.android.app.myfiles.util.SemFwWrapper;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.nio.charset.Charset;

public class SccFileUtil {
    private static final String TAG = "SccFileUtil";

    public static String getMimetypeFromSCCFile(String path) {
        String ret = "";
        String result = getSccMimeType(path);
        if (result != null && result.contains(MimeType.SEC_FILE)) {
            ret = result.trim();
        }

        return ret;
    }

    private static String getSccMimeType(String path) {
        String ret = null;
        File sccFile = SemFwWrapper.file(path);

        try (FileInputStream fis = new FileInputStream(sccFile)) {
            byte[] pkLenBuf = new byte[4];
            byte[] mimeTypeBuf = new byte[128];

            if (fis.skip(22) < 0) {
                Log.e(TAG, "getSccMimeType- need checking for skip(22)");
            }
            int len = fis.read(pkLenBuf, 0, 4);
            if (len < 0) {
                Log.e(TAG, "getSccMimeType - need checking for read(pkLenBuf, 0, 4)");
            }
            int pkLen = byteToInt(pkLenBuf, ByteOrder.LITTLE_ENDIAN);
            if (fis.skip(12) < 0) {
                Log.e(TAG, "getSccMimeType - need checking for skip(12)");
            }
            int readLen = fis.read(mimeTypeBuf, 0, pkLen);
            if (readLen < 0) {
                Log.e(TAG, "getSccMimeType - need checking for read(mimeTypeBuf, 0, pkLen)");
            }
            ret = new String(mimeTypeBuf, Charset.defaultCharset());

        } catch (IOException e) {
            Log.e(TAG, "IOException:" + e.toString());
        } catch (ArrayIndexOutOfBoundsException e) {
            Log.e(TAG, "ArrayIndexOutOfBoundsException:" + e.toString());
        }
        return ret;
    }

    public static boolean isSCCFile(String path) {
        boolean bRet = false;
        String result = getSccMimeType(path);
        if (result != null && result.contains(MimeType.SEC_FILE)) {
            bRet = true;
        }
        return bRet;
    }

    private static int byteToInt(byte[] bytes, ByteOrder order) {
        ByteBuffer buff = ByteBuffer.allocate(4);
        buff.order(order);
        buff.put(bytes);
        buff.flip();
        return buff.getInt();
    }

}
